<template>
  <div class="option">
    <van-form label-align="left" label-width="6em" :colon="false">
      <!-- 代码仓库 -->
      <van-cell :title="i18n('option-readme')" value="GitHub" 
        is-link url="https://github.com/meow42/tenvi-avatar/" />
      <van-cell v-show="$store.state.language === 'cn'" title="国内镜像仓库" value="Gitee"
        is-link url="https://gitee.com/tenvix/avatar-box/" />
      <!-- 通用设置 -->
      <van-divider content-position="center" style="marginTop: 0px;">{{ i18n('option-group-common') }}</van-divider>
      <!-- 用户登记 -->
      <van-field :label="i18n('option-user')" class="user">
        <template #input>
          <span v-show="!isUserEditable">{{ user.name ? '@' + user.name : i18n('anonymous') }}</span>
          <van-field v-show="isUserEditable" v-model="userInfoInput" :placeholder="i18n('tips-userId')" />
        </template>
        <template #extra>
          <van-button size="mini" plain type="primary" icon="exchange" v-show="!isUserEditable"
            @click="isUserEditable = true">{{ i18n('options-changeUser') }}</van-button>
          <van-button size="mini" plain icon="close" v-show="isUserEditable"
            @click="isUserEditable = false">{{ i18n('options-cancel') }}</van-button>
          <van-button size="mini" plain type="primary" icon="certificate" v-show="isUserEditable"
            @click="changeUser">{{ i18n('options-confirm') }}</van-button>
        </template>
      </van-field>
      <!-- 存档操作 -->
      <van-field :label="i18n('option-data')" class="user">
        <template #input>
          <van-uploader ref="jsonUploader" :after-read="importUserData" accept=".json" result-type="text"
            class="uploader-mini" v-show="false"></van-uploader>
          <van-button plain type="primary" size="mini" icon="orders-o"
            @click="$refs.jsonUploader.chooseFile()">{{ i18n('options-import') }}</van-button>
          <van-button plain type="primary" size="mini" icon="down" 
            @click="exportFrameNote">{{ i18n('options-export') }}</van-button>
          <van-button plain type="primary" size="mini" icon="ascending" :disabled="!user.id"
            @click="uploadFrameNote">{{ i18n('options-push') }}</van-button>
          <van-button plain type="primary" size="mini" icon="descending"
            @click="loadFrameNote">{{ i18n('options-pull') }}</van-button>
        </template>
      </van-field>
      <!-- 角色编辑相关设置 -->
      <van-divider content-position="center">{{ i18n('option-group-avatar') }}</van-divider>
      <van-field name="radio" :label="i18n('option-selectionTips')">
        <template #input>
          <van-radio-group v-model="option.avatarSelectionTips" direction="horizontal" 
            @change="(name) => { submit('avatarSelectionTips', name); }">
            <van-radio name="none">{{ i18n('options-none') }}</van-radio>
            <van-radio name="preview">{{ i18n('options-preview') }}</van-radio>
            <van-radio name="raw">{{ i18n('options-raw') }}</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field name="radio" :label="i18n('option-listMode')">
        <template #input>
          <van-radio-group v-model="option.avatarListMode" direction="horizontal" 
            @change="(name) => { submit('avatarListMode', name); }">
            <van-radio name="none">{{ i18n('options-none') }}</van-radio>
            <van-radio name="asc">{{ i18n('options-asc') }}</van-radio>
            <van-radio name="group">{{ i18n('options-group') }}</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <!-- 动作编辑相关设置 -->
      <van-divider content-position="center">{{ i18n('option-group-action') }}</van-divider>
      <!-- 图像背景 -->
      <van-field name="radio" :label="i18n('option-canvasBackground')">
        <template #input>
          <van-radio-group v-model="option.canvasBackground" direction="horizontal" 
            @change="(name) => { submit('canvasBackground', name); }">
            <van-radio name="none">{{ i18n('options-none') }}</van-radio>
            <van-radio name="axis">{{ i18n('options-axis') }}</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <!-- 动作帧备注 -->
      <van-field :label="i18n('option-frameNote')">
        <template #input>
          <van-checkbox v-model="option.showFrameNote" shape="square">{{ i18n('options-enable') }}</van-checkbox>
        </template>
      </van-field>
      <!-- 其他设置、操作 -->
      <van-divider content-position="center">{{ i18n('option-group-others') }}</van-divider>

      <van-field :label="i18n('option-hideImage')">
        <template #input>
          <van-switch v-model="option.hideImage" size="22px" />
        </template>
        <template #extra>
          <!-- 清除本地配置 -->
          <van-button plain type="danger" size="mini" icon="delete-o" 
            @click="cleanupLocalStorage"
          >{{ i18n('option-localStorageCleanup') }}</van-button>
        </template>
      </van-field>
    </van-form>
    <van-dialog v-model:show="showDialog" title="" show-cancel-button>
    </van-dialog>
  </div>
</template>
 
<script>
module.exports = {
  data() {
    return {
      userInfoInput: '',
      isUserEditable: false,
      showDialog: false,
      userInfoLoading: false,
    };
  },
  computed: {
    /** 全局配置的选项对象 */
    option() {
      return this.$store.state.option;
    },
    /** 全局配置的用户对象 */
    user() {
      return this.$store.state.user;
    },
    /** 在线存储的动作帧备注文件的URL */
    frameNoteURL() {
      return 'https://tenvix.meow42.cn/upload/avatar-box/user-cc/frame-note.json';
    },
  },
  mounted() {
    this.userInfoInput = this.$store.state.user.id;
    //console.log("ViewOption.mounted()", this);
  },
  methods: {
    /** 获取多语言文本 */
    i18n(key, upperFirst) {
      let result = this.$store.getters.i18n(key);
      return upperFirst ? _.upperFirst(result) : result;
    },
    /** 提交变更的选项 */
    submit(key, value) {
      //console.log('submit:', {key: key, value: value});
      this.$store.commit('setOption', {key: key, value: value});
    },
    /** 用户变更 */
    changeUser() {
      if (this.userInfoLoading) return;
      // 为空则注销用户
      if (!this.userInfoInput) {
        this.$store.commit('setUserInfo', {});
        this.isUserEditable = false;
        return;
      }
      // 尝试变更用户
      let that = this;
      this.userInfoLoading = true;
      fetch(this.$store.state.apiDomain + 'tenvix/user/' + this.userInfoInput)
        .then(response => response.json())
        .then(json => {
          if (!json['name']) throw 'User Not Exist';
          this.$store.commit('setUserInfo', { id: this.userInfoInput, name: json['name'] });
          window.vant.Notify({ type: 'success', message: this.i18n('tips-success') });
          this.isUserEditable = false;
        })
        .catch(err => {
          console.log('ChangeUser Failed:', err);
          window.vant.Notify({ type: 'warning', message: this.i18n('tips-failed') });
        })
        .finally(() => { that.userInfoLoading = false; });
    },
    /** 清理本地存储 */
    cleanupLocalStorage() {
      window.vant.Dialog.confirm({ 
        title: this.i18n('option-localStorageCleanup'), 
        confirmButtonText: this.i18n('options-confirm'),
        cancelButtonText: this.i18n('options-cancel'),
        //message: '弹窗内容', 
      })
        .then(() => { window.localStorage.removeItem("vuex"); })
        .catch(() => { }); // on cancel
    },
    /** 导入用户数据 */
    importUserData(uploadObj) {
      if (uploadObj && uploadObj.content)
        this.$store.commit('setFrameNote', JSON.parse(uploadObj.content));
    },
    /** 导出动作帧备注信息 需要 FileSaver */
    exportFrameNote() {
      let fileText = JSON.stringify(this.$store.state.frameNote);
      saveAs(new File([fileText], 'FrameNote.json', { type: 'text/plain;charset=utf-8' })); 
    },
    /** 弹出动作帧备注配置在线地址确认对话框 */
    
    /** 载入在线的动作帧备注信息 */
    loadFrameNote(uploadObj) {
      let that = this;
      window.vant.Dialog.confirm({ 
        title: this.i18n('options-pull'), 
        message: this.frameNoteURL,
        confirmButtonText: this.i18n('options-confirm'),
        cancelButtonText: this.i18n('options-cancel'),
      })
        .then(() => {
          store.dispatch('loadFile', { url: that.frameNoteURL, type: 'json' })
            .then(json => {
              that.$store.commit('setFrameNote', json);
              window.vant.Notify({ type: 'success', message: that.i18n('tips-success') });
            })
            .catch(err => {
              console.error('loadFrameNote => error', err);
              window.vant.Notify({ type: 'success', message: that.i18n('tips-failed') });
            });
        })
        .catch(() => { });
    },
    /** 上传动作帧备注信息 */
    uploadFrameNote() {
      window.vant.Dialog.confirm({ 
        title: this.i18n('tips-pushToCloud'), 
        confirmButtonText: this.i18n('options-confirm'),
        cancelButtonText: this.i18n('options-cancel'),
      })
        .then(() => {
          //window.vant.Notify({ type: 'success', message: that.i18n('tips-success') });
        })
        .catch(() => { }); // on cancel
    },
  },
};
</script>
